package com.lesserpand.rabbitmq.redis.service;

import org.redisson.Redisson;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author bailuo
 * @version 2.0
 * @Description redisson 延迟队列
 * @Date Created in 2019/1/15 9:31
 */
@Service("delayedQueueService")
public class DelayedQueueService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DelayedQueueService.class);

    @Autowired
    private RedissonClient redissonClient;

    public void sendMessageQueue() {

        // 真正的消息队列
        RQueue<String> distinationQueue = redissonClient.getQueue("message_queue");
        // 延迟队列，消息到时间后发送到真正的消息队列
        RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(distinationQueue);
        // 10秒钟以后将消息发送到指定队列
        delayedQueue.offer("msg1", 10, TimeUnit.SECONDS);
        // 一分钟以后将消息发送到指定队列
        delayedQueue.offer("msg2", 1, TimeUnit.MINUTES);
    }

    public String getMessageQueue() {
        RQueue<String> distinationQueue = redissonClient.getQueue("message_queue");
        String msg = distinationQueue.poll();
        return msg;
    }

}
